<?php
namespace Home\Controller;
use Home\Controller\EmptyController;
class PublicController extends EmptyController {

    public function login(){

        if(IS_POST){
            $username = trim(I('user_name'));
            $password = trim(I('password'));
            if($username && $password){
                $map['username'] = array('eq',$username);
                $map['password'] = array('eq',md5($password));
                $user_info = M('User')->where($map)->find();

                if(!empty($user_info)){
                    $_SESSION[C('USER_AUTO_KEY')] = $user_info['id'];
                    $this->redirect('Index/index');
                }else{
                    $this->error('用户名或密码错误!');
                }               
            }else{
                $this->error('请输入用户名和密码!');
            }
        }else{
            $this->display();
        }
    	
    }

    public function logout(){
    	unset($_SESSION[C('USER_AUTO_KEY')]);
    	$this->redirect('Public/login');
    }



    public function createMenu(){

        $model = M('AuthRule');
        $subQuery = $model->field('id')->where('pid = 1 and status = 1')->buildSql();
        $menu_arr = $model->field('id,pid,icon,title,name')->where('status = 1 and id or pid in '.$subQuery)->order('sort')->select();
        $menu_str = '';
        $action = MODULE_NAME.'/'.CONTROLLER_NAME .'/'.ACTION_NAME;
        foreach ($menu_arr as $key => $value) {
            $active = $value['name'] == $action?'class="active"':'';

            if($value['pid'] == 1){
                $child_str = '';
                $i = 0;
                $submenu = 'submenu';
                foreach ($menu_arr as $k => $v) {
                    if($v['pid'] == $value['id']){
                        $child_active = '';
                        if($v['name'] == $action){
                            $submenu = 'submenu open';
                            $child_active = 'class="active"';
                        }
                        $child_str .= '<li '.$child_active.'><a href="'.U($v['name']).'">'.$v['title'].'</a></li>';
                        $i++;
                    }
                }
                if($child_str == ''){
                    $menu_str .= '<li '.$active.'><a href="'.U($value['name']).'"><i class="icon '.$value['icon'].'"></i> <span>'.$value['title'].'</span></a></li>';
                }else{
                    $menu_str .= '<li class="'.$submenu.'"> <a href="#"><i class="icon icon-th-list"></i> <span>'.$value['title'].'</span> <span class="label label-important">'.$i.'</span></a>';
                    $menu_str .= '<ul>'.$child_str.'</ul></li>';
                }
            }    
        }
        return $menu_str;
    }


}	